const express = require("express");
const udRouter = express.Router();
const pool = require("../pool.js");
// 导入multiparty包，用于处理上传文件
const multiparty = require("multiparty");
// 导入fs包，用于处理文件系统
const fs = require("fs");

// 下载文件
udRouter.get("/download", (req, res) => {
  const file = req.query.file;
  const path = "public/uploads/" + file;
  res.download(path, file, (err) => {
    if (err) {
      console.log(err);
      res.send({
        code: 500,
        message: "下载失败",
      });
    } else {
      console.log("下载成功");
    }
  });
});

// 上传文件
udRouter.post("/upload", (req, res) => {
  var form = new multiparty.Form();
  form.uploadDir = "public/uploads"; //上传图片保存的地址(目录必须存在)
  form.parse(req, function (err, fields, files) {
    // 1、fields:获取表单的数据 2、files：图片上传成功返回的信息
    const file = files.file[0];
    // console.log(file);
    let newPath = form.uploadDir + "/" + file.originalFilename;
    fs.renameSync(file.path, newPath);
    let url = "http://192.168.10.23:5000/uploads/" + file.originalFilename;
    res.setHeader("Content-Type", "application/octet-stream");
    res.send({
      code: 200,
      message: "上传成功",
      path: url,
      name: file.originalFilename,
    });
  });
});

module.exports = udRouter;
